<template>
  <a-spin :spinning="getTreeLoading || getListLoading">
    <div class="main">
      <div class="org-tree">
        <div class="tree-list">
          <div class="title">选择班级</div>
          <div class="search">
            <a-input v-model:value="searchValue" placeholder="请输入关键词" @keyup.enter="onSearch">
              <template #prefix> <i class="iconfont icon-search-line" @click="onSearch"></i> </template>
            </a-input>
          </div>
          <div class="tree my-scrollbar">
            <a-tree
              v-if="treeData?.length"
              v-model:selectedKeys="selectedKeys"
              v-model:checkedKeys="checkedKeys"
              :default-expand-all="true"
              :auto-expand-parent="true"
              :field-names="{ children: 'children', title: 'name', key: 'id' }"
              class="tree-class"
              :selectable="false"
              checkable
              :tree-data="treeData"
              @check="onCheck"
            >
              <template #switcherIcon="{ switcherCls }"><down-outlined :class="switcherCls" /></template>
              <template #title="{ name }">
                {{ name }}
              </template>
            </a-tree>
          </div>
        </div>

        <div class="result-list">
          <div class="header-wrap">
            <div class="org-num">
              <span>已选&nbsp;</span><span class="num">{{ checkedResults.length }}个组织</span>
            </div>
            <div class="clear" @click="clear">清空</div>
          </div>

          <div class="checked-list">
            <div v-for="(item, index) in checkedResults" :key="index" class="checked-item">
              <div class="name" :title="item.name as string">
                {{ item.name }}
              </div>
              <i class="cursor-pointer del text-color-4 icon-DeleteOutlined iconfont" @click="del(item.id)"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script setup lang="ts" name="account-list">
  import type { TreeProps } from 'ant-design-vue'
  import { ref, watch } from 'vue'
  import { useRequest } from 'vue-request'

  import { defaultProps } from './options'
  interface TreeNodeProps {
    getTreeDataApi: any
    getListDataApi: any
    fieldNames?: any
  }

  const props = withDefaults(defineProps<TreeNodeProps>(), defaultProps)
  const { loading: getTreeLoading, runAsync: runGetTreeData } = useRequest<ResponseData<any[]>>(props.getTreeDataApi)

  // 获取树结构数据
  const getTree = async () => {
    const { data } = await runGetTreeData({ authFlag: 1 })
    console.log('filterTreeData(data)：', filterTreeData(data))

    treeData.value = filterTreeData(data)
  }
  getTree()

  const filterTreeData = (data: any) => {
    function mapNode(node: any): any {
      return {
        id: node.id,
        name: node.orgName,
        level: node.level,
        disabled: !(node.isAuthActive && node.level === 5),
        children: node.children ? node.children.map(mapNode) : null
      }
    }

    return data.map(mapNode)
  }

  const { loading: getListLoading, runAsync: runGetListData } = useRequest<ResponseData<any>>(props.getListDataApi)
  const treeData = ref<TreeProps[]>()
  const selectedKeys = ref<string[]>([])
  const checkedKeys = ref<string[]>([])
  const checkedResults = ref<Record<string, any>[]>([])

  const searchValue = ref<string>('')
  const onSearch = async () => {
    if (searchValue.value === '') {
      getTree()
      return
    }
    const { data } = await runGetListData({ name: searchValue.value })
    console.log('data:', data)
    treeData.value = data
  }
  const onCheck = (checkedKeys: any, e: { checked: any; checkedNodes: any; node: any; event: any }) => {
    const newCheckedNodes = e.checkedNodes
    const currentCheckedIds = new Set(newCheckedNodes.map((node: any) => node.id))

    // 去除包含相同数据的一项
    checkedResults.value = checkedResults.value.filter(item => currentCheckedIds.has(item.id))

    // 放入新的符合id的数据
    newCheckedNodes.forEach((node: any) => {
      if (!checkedResults.value.some(existingItem => existingItem.id === node.id)) {
        checkedResults.value.push(node)
      }
    })

    console.log('checkedNodes:=====', newCheckedNodes)
    console.log('checkedResults.value:', checkedResults.value)
  }

  const del = (id: string) => {
    checkedResults.value = checkedResults.value.filter(item => item.id !== id)
    checkedKeys.value = checkedKeys.value.filter(item => item !== id)
  }

  // 清空
  const clear = () => {
    checkedResults.value = []
    checkedKeys.value = []
  }
</script>

<style lang="less" scoped>
  // 当前页面不需要的话, 可删除 style标签

  .main {
    .org-tree {
      display: flex;
      width: 704px;
      border: 1px solid #d9d9db;
      border-radius: 6px;

      .tree-list {
        // width: 352px;
        height: 400px;
        background-color: #fff;
        flex: 1;
        border-radius: 6px;
        border-right: 1px solid #d9d9db;

        .type {
          padding: 0 8px;
          height: 20px;
          font-size: 12px;
          color: #fff;
          background: rgba(0, 0, 0, 0.3);
          border-radius: 12px;
          font-weight: 700;
          line-height: 20px;
          gap: 2px;
        }

        .title {
          padding: 6px 12px;
          color: rgba(21, 23, 27, 0.95);
          background: #fafafa;
          border-top-left-radius: 6px;
          border-top-right-radius: 6px;
          border-bottom: 1px solid #e8e8eb;
          font-weight: 700;
          line-height: 22px;
        }

        .search {
          padding: 8px 12px;
        }

        .tree {
          overflow: auto;
          padding: 4px 12px;
          margin-right: 4px;
          height: 303px;

          :deep(.ant-tree) {
            background: #fff !important;

            .name {
              overflow: hidden;
              max-width: 244px;
              text-overflow: ellipsis;
              white-space: nowrap;
              word-break: break-all;
              word-wrap: break-word;
            }
          }
        }
      }

      .result-list {
        // width: 352px;
        height: 400px;
        background-color: #fff;
        flex: 1;

        .header-wrap {
          display: flex;
          justify-content: space-between;
          padding: 6px 12px;
          background: #fafafa;
          border-top-left-radius: 6px;
          border-top-right-radius: 6px;
          border-bottom: 1px solid #e8e8eb;
          line-height: 22px;

          .org-num {
            font-weight: 700;
            color: rgba(21, 23, 27, 0.95);

            .num {
              font-weight: 400;
              color: rgba(25, 25, 48, 0.75);
            }
          }

          .clear {
            color: rgba(0, 156, 248, 1);
            cursor: pointer;
          }
        }

        .checked-list {
          overflow: auto;
          padding: 8px 12px;
          margin-right: 4px;
          height: 365px;

          .checked-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            line-height: 22px;

            .name {
              overflow: hidden;
              max-width: 294px;
              text-overflow: ellipsis;
              white-space: nowrap;
              color: rgba(16, 16, 20, 0.95);
              word-break: break-all;
              word-wrap: break-word;
            }
          }
        }
      }
    }
  }
</style>
